package com.youkeda.yikao.web.control;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.util.Properties;

/**
 * @author ：xiong
 * @date ：Created in 2019/9/6 10:08
 * @description：突破按验证初始化
 * @modified By：
 */
@Controller
public class CaptchaControl {
   //自动依赖注入
   @Autowired
   private DefaultKaptcha kaptcha;
   //HTTP响应头信息
    @RequestMapping(path = "/captcha")
    public void getCapacha(HttpServletResponse response, HttpSession session)throws Exception{
        //
        response.setDateHeader("Expires",0);
        //
        response.setHeader("Cache_Control","no-strore,no-cache,must-revalidate");
        //
        response.addHeader("Cache-Control","post-check=0,pre-check=0");
        //
        response.setHeader("Pragma","no-cache");
        //设置http内容格式
        String capText=kaptcha.createText();
        //产生随机数,并将随机数希尔到session中
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY,capText);
        //输出图片
        //将随机数写入图片
        BufferedImage bi=kaptcha.createImage(capText);
        //
        ServletOutputStream out=response.getOutputStream();

        ImageIO.write(bi,"png",out);
        try{
            out.flush();
        }finally {
            out.close();
        }
    }
    //初始化kaptcha
    @Bean
    public DefaultKaptcha initKaptcha(){
        DefaultKaptcha kaptcha=new DefaultKaptcha();
        Properties properties=new Properties();
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_CHAR_STRING,"0123456789abcdefg");
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH,"6");
//        properties.put(Constants.KAPTCHA_IMAGE_WIDTH,"267");
//        properties.put(Constants.KAPTCHA_IMAGE_WIDTH,"55");

        Config config=new Config(properties);
        kaptcha.setConfig(config);
        return kaptcha;
    }
}
